package sisi;

import java.util.List;

import javax.persistence.EntityManager;

public class ConfigurationController{

	private EntityManager getEntityManager() {
		return new sisi.MyEmf().getEntityManager();
	}

	public Configuration[] get(String cerca) {
		List<Configuration> lista = getList(cerca);
			return lista.toArray(new Configuration[0]);
		}

	@SuppressWarnings("unchecked")
	public List<Configuration> getList(String cerca) {

		String cWhere = "";
		if (cerca != null && !cerca.isEmpty()) {
			cWhere = " WHERE TRIM( BOTH FROM UPPER(c.agentnomination) ) LIKE :cerca ";
		}

		EntityManager em = getEntityManager();
		try {
			javax.persistence.Query q = em
				.createQuery("select c from Configuration as c " + cWhere 
					+ " order by c.agentnomination ");

			if (cerca != null && !cerca.isEmpty()) {
				q.setParameter("cerca", '%'+cerca.trim().toUpperCase()+'%' );
			}

			List<Configuration> lista = q.getResultList();
			return lista;
		} finally {
			em.close();
		}
	}

	public Configuration getxId(int id) {

		EntityManager em = getEntityManager();
		try {
			Configuration configurationx = em.find(Configuration.class, id);
			return configurationx;
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("finally")
	public Configuration add(Configuration configuration) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(configuration);
			em.getTransaction().commit();
			configuration = refresh(configuration);
		} finally {
			em.close();
			return configuration;
		}
	}

	@SuppressWarnings("finally")
	public boolean update(Configuration configuration) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Configuration configurationx = em.find(Configuration.class, configuration.getId());
			configurationx.setId(configuration.getId());
			configurationx.setAgentnomination(configuration.getAgentnomination());
			configurationx.setAgentinformation(configuration.getAgentinformation());
			em.getTransaction().commit();
			em.flush();

		} finally {
			em.close();
		return false;
		}
	}

@SuppressWarnings("finally")
public Configuration refresh(Configuration configuration) {

		Configuration configurationx = configuration;
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			configurationx = em.find(Configuration.class, configuration.getId());
			em.flush();
			em.refresh(configurationx);
		} finally {
			em.close();
			return configurationx;
		}
}

@SuppressWarnings("finally")
public boolean remove(Configuration configuration) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Configuration configurationx = em.find(Configuration.class, configuration.getId());
			em.remove(configurationx);
			em.getTransaction().commit();
		} finally {
			em.close();
			return false;
		}
}

}
//
// fine
